package pl.put.miasi.volleyball;


import java.io.File;

import javax.imageio.ImageIO;

import org.jbox2d.collision.CircleDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.World;

import processing.core.PImage;

public class B2Ball {

	private World world;
	private Main main;
	private Volleyball volleyball;
	
	private CircleDef ballShapeDef;
	private BodyDef ballBodyDef;
	private Body ballBody;

	public B2Ball(Volleyball volleyball) {
		this.volleyball = volleyball;
		this.world =  this.volleyball.m_world;
		this.main = this.volleyball.parent;
	}

	public void initialize() {
		PImage ballImage = null;
		try {
			 	
			ballImage = new PImage(ImageIO.read(new File("images/ball.gif")));
			ballImage.format = 2;
		} catch (Exception e) {
			e.printStackTrace();
		}
		/*
		 * Create ball
		 */

		// Ball Fixture Definition
		// CircleDef
		ballShapeDef = new CircleDef();
		ballShapeDef.density = Settings.BALL_DENSITY;
		ballShapeDef.friction = Settings.BALL_FRICTION;
		ballShapeDef.restitution = Settings.BALL_RESTITUTION;
		ballShapeDef.radius = Settings.BALL_RADIUS;

		// Ball Body Definition
		ballBodyDef = new BodyDef();
		ballBodyDef.allowSleep = false;
		ballBodyDef.position.set(Settings.INITIAL_BALL_POS);
		// to prevent tunnelling through bodies
		// if ball is fast
		ballBodyDef.isBullet = true;

		// Create ball body
		// Body
		ballBody = world.createDynamicBody(ballBodyDef);
		ballBody.setAngularVelocity(main.random(-50.0f, 50.0f));

		// Connect body and fixture
		ballBody.createShape(ballShapeDef);

		// Calculate mass from fixture parameters
		ballBody.setMassFromShapes();
		volleyball.bindImage(ballImage, new Vec2(0.0f, 0.0f), 0.0f, 1.0f / Settings.CS,
				ballBody);
		ballBody.m_userData = "ball";
		ballBodyDef.userData = "ball";
		ballShapeDef.userData = "ball";

	}
	
	public Body getBallBody() {
		return ballBody;
	}
}
